package handlers

import (
	"net/http"

	"grpc-jwt-yonghurenzheng/v1.1_session_cookies/config"

	"github.com/gin-gonic/gin"
)

// AuthRequired 是一个认证中间件
func AuthRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		session, err := config.Store.Get(c.Request, "user-session")
		if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "无法获取会话"})
			return
		}

		// 检查认证状态
		if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "未授权访问，请先登录"})
			return
		}

		// 将用户信息存入 gin.Context，方便后续的 Handler 使用
		c.Set("userID", session.Values["user_id"])
		c.Set("username", session.Values["username"])

		// 继续处理请求
		c.Next()
	}
}